package com.gin.kotlin.no_gay_alliance.provider.ngaphp

import android.util.Log
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.UserCenterArgument
import com.gin.kotlin.no_gay_alliance.database.entity.IpLocationHistory
import com.gin.kotlin.no_gay_alliance.model.UserDetailModel
import com.gin.nga.main.NgaApi
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.base.SingleData
import com.gin.nga.response.user.UserDetail
import retrofit2.Call
import java.lang.ref.WeakReference
import java.time.ZonedDateTime
import java.util.concurrent.TimeUnit

/**
 * 用户信息提供者
 */
class UserInfoProvider private constructor() : AbstractCachedDataProvider<UserCenterArgument, SingleData<UserDetail>, UserDetailModel>(
    javaType = TYPE_FACTORY.constructType(UserDetailModel::class.java),
    expires = TimeUnit.HOURS.toSeconds(3)
) {
    override val dir = "USER_INFO"

    override fun transform(rawData: SingleData<UserDetail>) = UserDetailModel(rawData.data!!, ZonedDateTime.now())

    override fun requestMethod(ngaApi: NgaApi, params: UserCenterArgument?): Call<NgaResponse<SingleData<UserDetail>>> {
        val p = params ?: throw RuntimeException("必须提供参数")
        val api = App.INSTANCE.ngaApi.userApi
        return if (p.html) api.infoHtml(p.userId, p.username) else api.info(p.userId, p.username)
    }

    override fun onSuccess(data: NgaResponse<SingleData<UserDetail>>?) {
        super.onSuccess(data)

        // 写入IP属地历史
        data?.data?.data?.also {
            Log.i(TAG, "记录IP属地历史: ${it.username}: ${it.ipLocation}")
            App.INSTANCE.database.ipLocationHistoryDao().add(
                IpLocationHistory(
                    id = 0,
                    timestamp = ZonedDateTime.now(),
                    userId = it.userId!!,
                    location = it.ipLocation!!
                )
            )
        }
    }

    override fun obtainRelativePath(userId: Long, params: UserCenterArgument?) = "${params?.userId}_${params?.username}_${params?.html == true}.json"

    companion object {
        private var instance: WeakReference<UserInfoProvider> = WeakReference(UserInfoProvider())
        fun getInstance(): UserInfoProvider = instance.get() ?: UserInfoProvider().also { instance = WeakReference(it) }
    }
}